package com.atguigu05.communication;

/**
 * ClassName: PrintNumnerTest
 * Package: com.atguigu05.communication
 * Description:
 *
 * @Author ZY
 * @Create 14:55
 * @Version 1.0
 */

class PrintNumber implements Runnable{

    private int number = 1;
    Object obj = new Object();

    @Override
    public void run() {

        while(true){

//            synchronized (this) {
            synchronized (obj) {

                //省略了this.notify()
//                notify();//唤醒正在等待的线程
                obj.notify();

                if (number <= 100){

                    try {
                        Thread.sleep(100);//sleep不会释放锁(同步监视器的调用)
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + ":" + number);
                    number++;

                    try {
                        //省略了this.wait()
//                        wait();//线程一旦执行此方法，会自动释放锁(同步监视器的调用)，进入等待池，等待被唤醒
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    break;
                }
            }
        }

    }
}



public class PrintNumnerTest {

    public static void main(String[] args) {

        PrintNumber p1 = new PrintNumber();
        Thread t1 = new Thread(p1,"线程1");
        Thread t2 = new Thread(p1,"线程2");

        t1.start();
        t2.start();

    }
}
